import React, { useState, memo, useEffect, useRef } from 'react';
import { Table, Dialog, Button, Row, Col, message, InputNumber, Input } from 'tdesign-react';
import { orderAddApi, paymentList, checkEmailApi, getPayMethodApi, getPayMethodRolesApi } from 'api/payment';
import classnames from 'classnames';
import CommonStyle from 'styles/common.module.less';
import useLoading from 'hooks/useLoading';
import {
  OPEN_TYPE_MAP,
  PACKAGE_TYPE_MAP,
  USER_TYPE_MAP,
  USER_TYPE_OPTIONS,
  ORDER_TYPE_OPTIONS,
  getOrderTypeLabel,
  IS_FIRST_PAY_MAPS,
  ORDER_STATUS_MAPS,
  PACKAGE_TYPE_OPTIONS,
} from 'constants/index';
import { PAYMENT_TYPE_MAP, ORDER_STATUS_MAP, ORDER_TYPE_MAP_S } from './consts';
import { createColumns } from 'utils/tableUtils';
import SakuraSearchForm from 'components/SakuraSearchForm';
import SakuraDrawer from 'components/SakuraDrawer';
import { mapToOptions, transformToField, createRequestParams } from 'utils';

import { SakuraDrawerRef } from 'components/SakuraDrawer/types';
import { USER_STATUS_OPTIONS } from 'pages/user/baseInfo/consts';
import { FormField } from 'types/Form';
import IppeakTable from 'components/IppeakTable';

export const SelectTable = () => {
  const [selectedRowKeys, setSelectedRowKeys] = useState<(string | number)[]>([0, 1]);
  const [visible, setVisible] = useState(false);
  const { loading, setLoading } = useLoading(false);
  const [opType, setOpType] = useState<'Add' | 'Edit'>('Add');
  const [editingItem, setEditingItem] = useState<any>(null);
  const drawerRef = useRef<SakuraDrawerRef | any>(null);
  const [time,setTime] = useState('hour')
  const [unlimitedTerm,setUnlimitedTerm] = useState(null)
  const [payMethods,setPayMethods]= useState<{ label: string; value: string | number }[]>([])
  const [initData,setInitData] = useState({
    status: 1,
    pack_type: '1',
    order_type: 9,
    email: '',
    flow: '',
    day: '',
    remarks: '',
  });
  const [limiter,setLimiter] = useState({min:1,max:30})
  const [unlTermPlace,setUnlimitedTermPlace] = useState('可输入1至23之间的整数')
  
  const clearFieldAtDate = (value: string) => {
    if(!value.length){
      delete query.start_time
      delete query.end_time
      setQuery((pre: any) => ({
        ...pre,
        page:1,
        page_size:pre.page_size || 10
      }))
    }
  }
  const fields: FormField[] = [
    { 
      label: '邮箱', 
      name: 'email', 
      type: 'input', 
      required: true,
      onChange: (_val: any, form?: any) => {
        try {
          form?.clearValidate?.(['email']);
        } catch {}
      },
      rules: [
        { required: true, message: '邮箱是必填项' },
        { validator: (val: any) => handleCheckEmail(val), trigger: 'blur' }
      ]
    },
    {
      label: '套餐类型',
      name: 'pack_type',
      type: 'select',
      options: PACKAGE_TYPE_OPTIONS.filter(item => (item.value != 3)).map(item=>({...item,value:Number(item.value)})) as { label: string; value: string | number }[],
      required: true,
      onChange:(value)=>{
        drawerRef.current.setFieldValue('flow','')
        drawerRef.current.setFieldValue('day','')
        drawerRef.current.setFieldValue('unlimited_day','')
        drawerRef.current.setFieldValue('bandwidth','')
        drawerRef.current.setFieldValue('remarks','')
      }
    },
    { 
      label: '流量', 
      name: 'flow', 
      type: 'inputNumber', 
      required: true, 
      appendSuffix: 'G',
      visible: (formValues) => !formValues.pack_type || formValues.pack_type === 1
    },
    { 
      label: '时效', 
      name: 'day', 
      type: 'inputNumber', 
      required: true, 
      appendSuffix: '天',
      visible: (formValues) => !formValues.pack_type || formValues.pack_type === 1 
    },
    { 
      label: '时效', 
      name: 'unlimited_day', 
      type: 's-input', 
      placeholder:unlTermPlace,
      max:limiter.max,
      required: true, 
      onChange:(value)=>{
        setUnlimitedTerm(value)
      },
      visible: (formValues) => formValues.pack_type === 6,
      sInputConfig:{
        selectOptions:[{label:'小时',value:'hour'},{label:'天',value:'day'}],
        selectName:'unlimited_term',
        callback:(value)=>{
          setTime(value)
          setUnlimitedTermPlace((pre)=>{
            if(value=='day'){
              setTime(value)
              return '可输入1至30之间的整数'
            }else{
              setTime(value)
              return '可输入1至23之间的整数'
            }
          })
        }
      }
    },
    { 
      label: '带宽', 
      name: 'bandwidth', 
      type: 'select', 
      options:[{label:'200',value:200},{label:'300',value:300},{label:'400',value:400},{label:'500',value:500},{label:'600',value:600},{label:'700',value:700},{label:'800',value:800},{label:'900',value:900},{label:'1000',value:1000}],
      required: true, 
      appendSuffix: 'Mbps',
      visible: (formValues) => formValues.pack_type === 6
    },
    {
      label: '订单类型',
      name: 'order_type',
      type: 'select',
      required: true,
      options: ORDER_TYPE_MAP_S,
      disabled: true,
      help: '试用订单仅针对当前没有套餐的用户生效；若已有套餐，添加试用套餐后，会覆盖已有套餐；',
    },
    { label: '备注', name: 'remarks', type: 'textarea', props: { autosize: { minRows: 3, maxRows: 10 } } },
  ];
  
  const columns = createColumns([
    {
      label: '订单号',
      key: 'order',
      width: '200',
    },
    {
      label: '用户ID',
      key: 'user_id',
    },
    {
      label: '邮箱',
      key: 'username',
      width: '180',
    },
    {
      label: '用户类型',
      key: 'tags',
      render({ row }: any) {
        return row.tags == 'vip' ? (
          <span style={{ color: '#7868e6', cursor: 'pointer' }}>{USER_TYPE_MAP[row.tags] || '-'}</span>
        ) : row.tags == 'staff' ? (
          <span style={{ color: '#f80', cursor: 'pointer' }}>{USER_TYPE_MAP[row.tags] || '-'}</span>
        ) : (
          USER_TYPE_MAP[row.tags] || '-'
        );
      },
    },

    {
      label: '套餐类型',
      key: 'pack_type',
      enumConf: {
        options: PACKAGE_TYPE_MAP,
      },
    },
    {
      label: '订单名称',
      key: 'title_name',
      width: '250',
    },
    {
      label: '订单金额',
      key: 'order_amount',
    },
    {
      label: '支付金额',
      key: 'actual_amount',
    },
    {
      label: '抵扣金额',
      key: 'deduction_amount',
    },
    {
      label: '支付方式',
      key: 'pay_name',
      width: '120',

    },
    {
      label: '支付状态',
      key: 'done',
      enumConf: {
        options: PAYMENT_TYPE_MAP,
      },
    },
    {
      label: '生成时间',
      key: 'created',
      type: 'date',
      width: '170',
    },
    {
      label: '支付时间',
      key: 'done_at',
      type: 'date',
      width: '170',
    },
    {
      label: '支付订单号',
      key: 'third_order_no',
      width: '180',
    },
    {
      label: '订单状态',
      key: 'type',
      enumConf: {
        options: ORDER_TYPE_OPTIONS,
      },
      render({ row }: any) {
        return row.type == 99 ? '异常' : '正常';
      },
    },

    {
      label: '来源',
      key: 'origin',
      width: '180',
    },
    {
      label: '订单类型',
      width: '200',
      key: 'source',
      render({ row }: any) {
        return `${ORDER_STATUS_MAP[row.source]}${
          [10, 9, 3].includes(row.type) ? `-${getOrderTypeLabel(row.type)}` : ''
        }`;
      },
    },
    {
      label: '开通状态',
      key: 'active_status',
      enumConf: {
        options: OPEN_TYPE_MAP,
      },
    },
    {
      label:'购买次数',
      key: 'is_gou',
      enumConf: {
        options: IS_FIRST_PAY_MAPS,
      },
    },
    {
      label: '套餐到期时间',
      key: 'expire',
      type: 'date',
      width: '200',
    },
    {
      label: '操作人',
      key: 'creator',
    },
    {
      label: '备注',
      key: 'remarks',
      width: '250',
    },
    // {
    //   fixed: 'right',
    //   key: 'op',
    //   width: 160,
    //   label: '操作',
    // },
  ]);
  const [table, setTable] = useState({
    list: [],
    total: 0,
    current: 1,
    pageSize: 10,
    total_price:0,
  });
  const [query, setQuery] = useState({
    page: 1,
    page_size: 10,
  });
  const formFields: any[] = [
    {
      label:'用户ID',
      name:'uid',
      type:'input',
      onChange:(value:any)=>{
        if(value==null || String(value).trim()===''){
          setQuery((prev:any)=>{
            const { uid, ...rest } = prev || {};
            return { ...rest };
          })
        }
      },
      colWrap:{
        colSpan: 1.5,
        labelWidth: 60,
      }
    },
    {
      label: '邮箱',
      name: 'username',
      type: 'input',
      onChange:(value:any)=>{
        if(value==null || String(value).trim()===''){
          setQuery((prev:any)=>{
            const { username, ...rest } = prev || {};
            return { ...rest };
          })
        }
      },
      colWrap: {
        colSpan: 1.5,
        labelWidth: 45,
      },
    },
    {
      label: '用户类型',
      name: 'tags',
      type: 'select',
      options: USER_TYPE_OPTIONS,
    },
    
    {
      label:'订单号',
      name:'order',
      type:'input',
      onChange:(value:any)=>{
        if(value==null || String(value).trim()===''){
          setQuery((prev:any)=>{
            const { order, ...rest } = prev || {};
            return { ...rest };
          })
        }
      },
      colWrap: {
        colSpan: 1.5,
        labelWidth: 60,
      },
    },
    {
      label:'支付单号',
      name:'th_order',
      type:'input',
      onChange:(value:any)=>{
        if(value==null || String(value).trim()===''){
          setQuery((prev:any)=>{
            const { th_order, ...rest } = prev || {};
            return { ...rest };
          })
        }
      },
      colWrap: {
        colSpan: 1.5,
        labelWidth: 75,
      },
    },
    {
      label:'套餐类型',
      name:'order_type',
      type:'select',
      options:PACKAGE_TYPE_OPTIONS,
      colWrap: {
        colSpan: 1.5,
        labelWidth: 75,
      },
    },
    {
      label:'支付方式',
      name:'pay_method',
      options:payMethods, 
      type:'select',
      colWrap: {
        colSpan: 1.5,
        labelWidth: 75,
      },
    },
    {
      label: '支付状态',
      name: 'done',
      type: 'select',
      options: mapToOptions(PAYMENT_TYPE_MAP),
      colWrap: {
        colSpan: 1.5,
        labelWidth: 75,
      },
    },
    {
      label: '订单状态',
      name: 'type',
      type: 'select',
      options: mapToOptions(ORDER_STATUS_MAPS),
      colWrap: {
        colSpan: 1.5,
        labelWidth: 75,
      },
    },
    {
      label: '订单类型',
      name: 'source',
      type: 'select',
      options: mapToOptions(ORDER_STATUS_MAP).map(item=>{
        if(item.value=='2'){
          return {
            label:'后台订单-试用',
            value:item.value
          }
        }else{
          return item
        }
      }),
      colWrap: {
        colSpan: 1.5,
        labelWidth: 75,
      },
    },
    {
      label:'购买次数',
      name:'is_gou',
      type:'select',
      options: mapToOptions(IS_FIRST_PAY_MAPS),
      colWrap: {
        colSpan: 1.5,
        labelWidth: 75,
      },
    },
    {
      label:'支付时间',
      type:'date',
      name:'pay_time',
      returnType:'timestamp',
      onChange:clearFieldAtDate

    },
  
   
  
   
   
  
    
  ];
  const { list, total, current, pageSize } = table;
  const handleCheckEmail = async (value: any) => {
    try {
      if (value == null || String(value).trim() === '') {
        // 交由必填规则处理
        return { result: true };
      }
      await checkEmailApi({ username: value });
      return { result: true };
    } catch (err: any) {
      return { result: false, message: '该邮箱不存在！' };
    }
  }
  const fetchUserList = async (params?: any) => {
    setLoading(true);
    try {
      // 合并参数并过滤空值
        delete query?.pay_time;
      const requestParams = createRequestParams({ ...params, ...query });
      const res: any = await paymentList(requestParams);
      setLoading(false);
      setTable((pre: any) => ({
        ...pre,
        list: res.results || [],
        total: res.total || 0,
        pageSize: res.page_size,
        total_price:res.total_amount,
        current: res.page,
      }));
    } catch (err) {
      console.log(err, 'err');
    }
  };

  function onSelectChange(value: (string | number)[]) {
    setSelectedRowKeys(value);
  }

  const handleAddClick = () => {
    setOpType('Add');
    setVisible(true);
  };
  const handleSubmitClick = async (type: string, values: any, cb: () => void) => {
    let params = {
      ...values,
      flow: Number(values.flow),
      day: Number(values.day),
      pack_type: Number(values.pack_type),
      order_type: Number(values.order_type),
    }
    if(values.pack_type==6){
      delete params.flow;
      if(!values.day){
        delete params.day
      }
      params = {
        ...params,
        [time]:Number(unlimitedTerm),
      }
      delete params.unlimited_day
    }
    try {
      if (type == 'Add') {
        const res = await orderAddApi(params);
        message.success('操作成功')
      } else {
        message.error('操作失败，请稍后重试~');
      }
    } catch (err: any) {
      if (err.response.data.code == 40050) {
        message.error('操作失败，请稍后重试~');
        drawerRef.current.setFieldValue('email', '');
      }
      return;
    }
    cb && cb();
    fetchUserList();
    setVisible(false);
  };
  useEffect(() => {
    fetchUserList();
  }, [query]);

  const getPayMethodFn = async()=>{
    const res:any = await getPayMethodApi();
    const rolesRes:any = await getPayMethodRolesApi();
    const allowedIds = new Set(JSON.parse(rolesRes?.results?.value) || []);
    setPayMethods(
      (res.results || [])
        .filter((item: any) => allowedIds.has(item.Id))
        .map((item: any) => ({ label: item.Remarks, value: item.Id }))
    )
  }
  useEffect(()=>{
    getPayMethodFn()
  },[])
  const handleSearch = (values: any) => {
    setQuery((pre) => ({
      ...values,
      start_time:values?.pay_time?.[0] ||'',
      end_time:values?.pay_time?.[1] ||'',
      page: 1,
      page_size:query.page_size
    }));
  };
  const handleReset = () => {
    setQuery((pre) => ({
      page: 1,
      page_size: 10,
    }));
  };
    // 统一的字段清除处理函数
    const handleFieldClear = (fieldName: string) => {
      setQuery((prev: any) => {
        const { [fieldName]: removed, ...rest } = prev || {};
        return { ...rest, };
      });
    };
  return (
    <>
      <Row>
        <Col>
          <SakuraSearchForm
            fields={formFields}
            createField={true}
            onSearch={handleSearch}
            onAddClick={handleAddClick}
            onReset={handleReset}
            onFieldClear={handleFieldClear}
          />
        </Col>
      </Row>
      <IppeakTable
        loading={loading}
        dataSource={list}
        columns={columns}
        rowKey='index'
        selectedRowKeys={selectedRowKeys}
        tableHeight={368}
        onSelectChange={onSelectChange}
        pagination={{
          pageSize,
          total,
          current,
          showJumper: true,
          totalContent:()=>{
          return (
            <span>
            共 {total} 条, 支付金额：{(table?.total_price||0)}
          </span>
          )
          },
          onCurrentChange(current: number, pageInfo: any) {
            const params = {
              ...query,
              page: pageInfo.current,
            };
            setQuery((pre) => ({
              ...pre,
              page: pageInfo.current,
            }));
          },
          onPageSizeChange(size: number) {
            const params = {
              ...query,
              page_size: size,
            };
            setQuery((pre) => ({
              ...pre,
              page_size: size,
            }));
          },
        }}
      />
      <SakuraDrawer
        ref={drawerRef}
        visible={visible}
        title={'订单'}
        onClose={() => {
          setVisible(false);
        }}
        onConfirm={handleSubmitClick}
        type={opType}
        initialValues={opType == 'Edit' ? editingItem : initData}
        drawerFormFields={fields}
        width="45%"
        size="medium"
        placement="right"
      ></SakuraDrawer>
    </>
  );
};

const selectPage: React.FC = () => (
  <div className={classnames(CommonStyle.pageWithPadding, CommonStyle.pageWithColor)}>
    <SelectTable />
  </div>
);

export default memo(selectPage);
